from sqlalchemy import create_engine

import false_email
from config import *


class HtmlOutputer(object):
    def __init__(self):
        self.f_email = false_email.FalseEmail()

    def to_maria(self, csv, db_name, table_name,num_retries=2):
        try:
            engine = create_engine(
                "mysql+pymysql://{0}:{1}@{2}:{3}/{4}?charset=utf8".format(
                    MYSQL_USER, MYSQL_PASSWD, MYSQL_HOST, MYSQL_PORT,
                    db_name), echo=False)
            csv.to_sql(table_name, con=engine, if_exists='append', index=False)
        except:
            content = "数据库连接失败"
            print(content)
            name = str(num_retries)
            self.f_email.send_email(content, name)
            if num_retries > 0:
                return self.to_maria(csv, num_retries - 1)
